package com.example.night.service.MysqlService;

import com.example.night.data.Good.GoodsRanking;
import com.example.night.data.Good.GoodsRankingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class GoodsRankingMysqlService {

    private final GoodsRankingRepository goodsRankingRepository;

    @Autowired
    public GoodsRankingMysqlService(GoodsRankingRepository goodsRankingRepository) {
        this.goodsRankingRepository = goodsRankingRepository;
    }

    // 保存榜单数据
    public GoodsRanking save(GoodsRanking goodsRanking) {
        return goodsRankingRepository.save(goodsRanking);
    }

    // 批量保存榜单数据
    public void save(List<GoodsRanking> goodsRankings) {
        goodsRankingRepository.saveAll(goodsRankings);
    }

    // 根据ID查询榜单项
    public Optional<GoodsRanking> findById(Long id) {
        return goodsRankingRepository.findById(id);
    }

    // 根据商品ID查询榜单项
    public GoodsRanking findByProductId(String relateProductId) {
        return goodsRankingRepository.findByGoodPackage_RelateProductId(relateProductId);
    }

    // 查询所有榜单项
    public List<GoodsRanking> findAll() {
        return goodsRankingRepository.findAll();
    }

    // 根据商品ID删除榜单项，并确保在事务上下文中执行
    @Transactional
    public void deleteByProductId(String relateProductId) {
        goodsRankingRepository.deleteByGoodPackage_RelateProductId(relateProductId);
    }

    // 清空所有榜单
    @Transactional
    public void clearAll() {
        goodsRankingRepository.deleteAll();
    }
}
